package com.rgst.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.rgst.comm.SearchParam;
import com.rgst.dao.entity.Enroll;
import com.rgst.dao.repository.BusiConfigRepository;
import com.rgst.dao.repository.BusiRepository;
import com.rgst.serivce.EnrollService;
import com.rgst.utils.DateUtil;

/**
 * Created by tancw on 2019/12/8.
 */
@Controller
@RequestMapping("enroll")
public class EnrollController {

    @Autowired
    private EnrollService enrollService;

    @Autowired
    private BusiRepository busiRepository;

    @Autowired
    private BusiConfigRepository busiConfigRepository;

    @RequestMapping("list")
    public ModelAndView list() {
        ModelAndView view = new ModelAndView();
        view.setViewName("rgst/enroll/list");
        view.addObject("sdate", DateUtil.addDays(-29));
        view.addObject("edate", DateUtil.now());
        view.addObject("busis", busiRepository.findAll(new Sort(Sort.Direction.ASC, "id")));
        view.addObject("grades", busiConfigRepository.findAllByType("grade"));
        view.addObject("classs", busiConfigRepository.findAllByType("class"));
        return view;
    }

    @ResponseBody
    @RequestMapping("list-data")
    public Page<Enroll> listData(SearchParam sp) {
        Pageable pageable = sp.getPageable(new Sort(Sort.Direction.ASC, "id"));
        final Map param = sp.getSpDown();
        return enrollService.listData(param, pageable);
    }

    @RequestMapping("download")
    public void download(SearchParam sp, HttpServletResponse response) throws IOException {
        Map<String, Object> param = sp.getSpDown();
        Pageable pageable = PageRequest.of(0, Integer.MAX_VALUE, new Sort(Sort.Direction.ASC, "id"));
        Workbook workbook = enrollService.getForExcel(param, pageable);
        if(workbook == null){
            throw new IllegalArgumentException("下载失败!");
        }
        String fileName = "报名信息" + DateUtil.format(new Date(), "yyyy-MM-dd") + ".xls";
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(fileName,"UTF-8"));
        OutputStream out = response.getOutputStream();
        workbook.write(out);
    }

}
